package controllers

import (
	"encoding/json"
	"github.com/astaxie/beego"
	"io/ioutil"
	"net/http"
)

type ApplyController struct {
	beego.Controller
}

func (this *ApplyController) Get() {
	this.Ctx.WriteString("Hello I am target .")
}

type RedirectController struct {
	beego.Controller
}

func (this *RedirectController) Get() {
	path := this.Ctx.Input.Param(":path")
	res, err := http.Get("http://localhost:8080/v1/expend?url=" + path)
	if err != nil {
		beego.Error("Http client get /v1/expend?url=", path, " error .")
	}
	data, err := ioutil.ReadAll(res.Body)
	res.Body.Close()
	if err != nil {
		beego.Error("Read /v1/expend response body error.")
	}
	pair := &UrlPair{}
	err = json.Unmarshal(data, &pair)
	if err != nil {
		beego.Error("Unmarshal /v1/expend response data error.")
	}
	this.Redirect(pair.Long, 301)
}
